import { z } from 'zod'
import {
  CreateResponsePayload,
  CreateRequestPayloadMulti,
} from '../connect/parser_executable_types'
import path from 'path'
import fs from 'fs'
import { generateProps } from '../react/create'
import * as prettier from 'prettier'
import { kebabCase } from 'lodash'
import { getOutFileName } from '../connect/create_common'

export async function createHtmlCodeConnect(
  payload: CreateRequestPayloadMulti,
): Promise<z.infer<typeof CreateResponsePayload>> {
  const { figmaConnections, normalizedName, destinationFile, destinationDir, sourceFilepath } =
    payload
  const component = figmaConnections[0].component
  const { figmaNodeUrl } = component

  const webComponentName = kebabCase(normalizedName)

  const sourceFilename = sourceFilepath
    ? path.parse(sourceFilepath).name.split('.')[0]
    : webComponentName

  const filePath = getOutFileName({
    outFile: destinationFile,
    outDir: destinationDir,
    sourceFilename,
    extension: 'ts',
  })

  const codeConnect = `
import figma, { html } from '@figma/code-connect/html'

/**
 * -- This file was auto-generated by \`figma connect create\` --
 * \`props\` includes a mapping from Figma properties and variants to
 * suggested values. You should update this to match the props of your
 * code component, and update the \`example\` function to return the
 * code example you'd like to see in Figma
*/

figma.connect("${figmaNodeUrl}", {
  props: ${generateProps(component)},
  example: (props) => html\`<${webComponentName} />\`
})
`

  let formatted = prettier.format(codeConnect, {
    parser: 'typescript',
    semi: false,
    trailingComma: 'all',
  })

  if (fs.existsSync(filePath)) {
    return {
      createdFiles: [],
      messages: [{ message: `File ${filePath} already exists, skipping creation`, level: 'ERROR' }],
    }
  }
  fs.mkdirSync(path.dirname(filePath), { recursive: true })
  fs.writeFileSync(filePath, formatted)

  return { createdFiles: [{ filePath }], messages: [] }
}
